<template>
  <div class="data-view">
    <!-- 数据概览表格 -->
    <el-card class="data-table-card">
      <template #header>
        <div class="table-header">
          <div class="table-title">📊 数据概览</div>
          <div class="table-actions">
            <el-button @click="refreshData">
              🔄 刷新
            </el-button>
            <el-button type="primary" @click="exportData">
              📤 导出
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="isLoading">
        <el-table-column prop="platform" label="平台" width="120">
          <template #default="{ row }">
            {{ row.platformIcon }} {{ row.platform }}
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="数据类型" width="150" />
        <el-table-column prop="totalCount" label="总数量" width="120">
          <template #default="{ row }">
            {{ row.totalCount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="todayCount" label="今日新增" width="120" />
        <el-table-column prop="lastUpdate" label="最后更新" width="150" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="viewData(row)">
              查看
            </el-button>
            <el-button size="small" type="primary" @click="exportSingle(row)">
              导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="tableData.length === 0 && !isLoading" class="empty-data">
        <el-empty description="暂无数据，请先在配置页面提交爬取任务" />
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card">
        <div class="stat-header">
          <div class="stat-title">📈 数据统计</div>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ totalDataCount.toLocaleString() }}</div>
          <div class="stat-label">总数据量</div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-header">
          <div class="stat-title">🔥 热门内容</div>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ hotContentCount }}</div>
          <div class="stat-label">高互动内容</div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-header">
          <div class="stat-title">💾 存储空间</div>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ storageUsed }}</div>
          <div class="stat-label">已使用空间</div>
        </div>
      </el-card>
    </div>

    <!-- 详细数据对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentPlatform} 数据详情`"
      width="90%"
      destroy-on-close
    >
      <div class="detail-header">
        <div class="detail-title">{{ currentDataType }}</div>
        <div class="detail-actions">
          <el-button size="small" @click="fetchDetailData">刷新</el-button>
        </div>
      </div>
      
      <el-table
        :data="detailData"
        style="width: 100%"
        v-loading="detailLoading"
        border
        stripe
      >
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="120" show-overflow-tooltip />
        <el-table-column label="互动数据" width="200">
          <template #default="{ row }">
            <div class="engagement-data">
              <div class="engagement-item">
                <i class="el-icon-thumb"></i> {{ row.likeCount }}
              </div>
              <div class="engagement-item">
                <i class="el-icon-chat-dot-round"></i> {{ row.commentCount }}
              </div>
              <div class="engagement-item">
                <i class="el-icon-share"></i> {{ row.shareCount }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="180" />
        <el-table-column prop="crawledAt" label="爬取时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openUrl(row.url)">
              查看原文
            </el-button>
            <el-button size="small" type="danger" @click="deleteData(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="detailData.length === 0 && !detailLoading" class="empty-data">
        <el-empty description="暂无详细数据" />
      </div>
      
      <el-pagination
        v-if="totalItems > 0"
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-dialog>

    <!-- 数据导出对话框 -->
    <el-dialog v-model="exportDialogVisible" title="导出数据" width="500px">
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
            <el-radio label="json">JSON</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="exportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="包含字段">
          <el-checkbox-group v-model="exportForm.fields">
            <el-checkbox label="title">标题</el-checkbox>
            <el-checkbox label="content">内容</el-checkbox>
            <el-checkbox label="author">作者</el-checkbox>
            <el-checkbox label="stats">统计数据</el-checkbox>
            <el-checkbox label="comments">评论</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExport">确认导出</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入API函数
interface DataOverview {
  platform: string
  platformIcon: string
  dataType: string
  totalCount: number
  todayCount: number
  lastUpdate: string
}

interface CrawledData {
  id: string
  platform: string
  dataType: string
  title: string
  content?: string
  author: string
  authorId: string
  url: string
  likeCount: number
  commentCount: number
  shareCount: number
  viewCount: number
  createdAt: string
  crawledAt: string
  keywords: string
}

// 数据概览
const tableData = ref<DataOverview[]>([])
const isLoading = ref(false)

// 详细数据
const detailData = ref<CrawledData[]>([])
const detailDialogVisible = ref(false)
const currentPlatform = ref('')
const currentDataType = ref('')
const detailLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

// 统计数据
const totalDataCount = computed(() => {
  return tableData.value.reduce((sum, item) => sum + item.totalCount, 0)
})

const hotContentCount = ref(0)
const storageUsed = ref('0MB')

// 导出相关
const exportDialogVisible = ref(false)
const exportForm = ref({
  format: 'excel',
  dateRange: [],
  fields: ['title', 'content', 'author', 'stats'],
})

// 获取数据概览
const fetchDataOverview = async () => {
  isLoading.value = true
  try {
    const { invoke } = await import('@tauri-apps/api/core')
    const result = await invoke('get_data_overview')
    console.log('获取到的数据概览:', result)
    
    if (Array.isArray(result)) {
      tableData.value = result.map(item => ({
        platform: item.platform,
        platformIcon: item.platform_icon,
        dataType: item.data_type,
        totalCount: item.total_count,
        todayCount: item.today_count,
        lastUpdate: item.last_update
      }))
    } else {
      console.error('返回的数据概览格式不正确:', result)
      ElMessage.error('获取数据概览失败')
    }
    
    // 计算热门内容数量（点赞数+评论数超过100的内容）
    calculateHotContent()
    
    // 计算存储空间使用情况
    calculateStorageUsage()
  } catch (error) {
    console.error('获取数据概览失败:', error)
    ElMessage.error(`获取数据概览失败: ${error}`)
  } finally {
    isLoading.value = false
  }
}

// 计算热门内容数量
const calculateHotContent = async () => {
  try {
    const { invoke } = await import('@tauri-apps/api/core')
    const stats = await invoke('get_statistics')
    console.log('获取到的统计数据:', stats)
    
    if (stats && typeof stats === 'object') {
      // 假设后端返回了热门内容的数量
      hotContentCount.value = (stats as any).hot_content || 0
    }
  } catch (error) {
    console.error('获取热门内容统计失败:', error)
    // 使用默认值
    hotContentCount.value = Math.floor(totalDataCount.value * 0.15)
  }
}

// 计算存储空间使用情况
const calculateStorageUsage = async () => {
  try {
    const { invoke } = await import('@tauri-apps/api/core')
    const systemInfo = await invoke('get_system_info')
    console.log('获取到的系统信息:', systemInfo)
    
    if (systemInfo && typeof systemInfo === 'object') {
      storageUsed.value = (systemInfo as any).disk_usage || '未知'
    }
  } catch (error) {
    console.error('获取存储空间使用情况失败:', error)
    // 使用默认值
    const totalBytes = totalDataCount.value * 5000 // 假设每条数据平均5KB
    if (totalBytes < 1024 * 1024) {
      storageUsed.value = `${(totalBytes / 1024).toFixed(2)}KB`
    } else if (totalBytes < 1024 * 1024 * 1024) {
      storageUsed.value = `${(totalBytes / (1024 * 1024)).toFixed(2)}MB`
    } else {
      storageUsed.value = `${(totalBytes / (1024 * 1024 * 1024)).toFixed(2)}GB`
    }
  }
}

// 刷新数据
const refreshData = async () => {
  await fetchDataOverview()
  ElMessage.success('数据已刷新')
}

// 查看详细数据
const viewData = async (row: any) => {
  currentPlatform.value = getPlatformCode(row.platform)
  currentDataType.value = row.dataType
  detailDialogVisible.value = true
  currentPage.value = 1
  
  await fetchDetailData()
}

// 获取平台代码
const getPlatformCode = (platformName: string): string => {
  const platformMap: Record<string, string> = {
    '小红书': 'xhs',
    '抖音': 'douyin',
    '快手': 'kuaishou',
    'B站': 'bilibili',
    '微博': 'weibo',
    '知乎': 'zhihu',
    '贴吧': 'tieba'
  }
  return platformMap[platformName] || platformName.toLowerCase()
}

// 获取详细数据
const fetchDetailData = async () => {
  detailLoading.value = true
  try {
    const { invoke } = await import('@tauri-apps/api/core')
    const result = await invoke('get_data_list', {
      platform: currentPlatform.value,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    console.log('获取到的详细数据:', result)
    
    if (Array.isArray(result)) {
      detailData.value = result.map(item => ({
        id: item.id,
        platform: item.platform,
        dataType: item.data_type,
        title: item.title,
        content: item.content,
        author: item.author,
        authorId: item.author_id,
        url: item.url,
        likeCount: item.like_count,
        commentCount: item.comment_count,
        shareCount: item.share_count,
        viewCount: item.view_count,
        createdAt: formatDateTime(item.created_at),
        crawledAt: formatDateTime(item.crawled_at),
        keywords: item.keywords
      }))
      
      // 获取总数量
      try {
        const count = await invoke('get_data_count', {
          platform: currentPlatform.value
        })
        totalItems.value = count as number
      } catch (error) {
        console.error('获取数据总数失败:', error)
        totalItems.value = detailData.value.length
      }
    } else {
      console.error('返回的详细数据格式不正确:', result)
      ElMessage.error('获取详细数据失败')
      detailData.value = []
    }
  } catch (error) {
    console.error('获取详细数据失败:', error)
    ElMessage.error(`获取详细数据失败: ${error}`)
    detailData.value = []
  } finally {
    detailLoading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string): string => {
  if (!dateTimeStr) return '未知'
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN')
  } catch (error) {
    return dateTimeStr
  }
}

// 页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchDetailData()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchDetailData()
}

// 导出数据
const exportData = () => {
  exportDialogVisible.value = true
}

  // 导出单个平台数据
  const exportSingle = async (row: any) => {
    try {
      const platform = getPlatformCode(row.platform)
      const { invoke } = await import('@tauri-apps/api/core')
      
      // 调用后端的save_file命令来保存文件
      const fileName = `${row.platform}_数据_${new Date().toISOString().slice(0, 10)}.xlsx`
      const filePath = await invoke('save_file', {
        content: '', // 这里内容为空，因为实际内容由export_data生成
        defaultName: fileName
      })
      
      if (filePath) {
        // 调用导出API
        await invoke('export_data', {
          options: {
            format: 'excel',
            platforms: [platform]
          },
          filePath
        })
        
        ElMessage.success(`${row.platform}的${row.dataType}数据已导出到: ${filePath}`)
      }
    } catch (error) {
      console.error('导出数据失败:', error)
      ElMessage.error(`导出失败: ${error}`)
    }
  }

  // 确认导出
  const confirmExport = async () => {
    try {
      const { invoke } = await import('@tauri-apps/api/core')
      
      // 获取文件扩展名
      const extension = exportForm.value.format === 'excel' ? 'xlsx' : 
                        exportForm.value.format === 'csv' ? 'csv' : 'json'
      
      // 使用后端的save_file命令来保存文件
      const fileName = `爬虫数据_${new Date().toISOString().slice(0, 10)}.${extension}`
      const filePath = await invoke('save_file', {
        content: '', // 这里内容为空，因为实际内容由export_data生成
        defaultName: fileName
      })
    
    if (filePath) {
      // 调用导出API
      await invoke('export_data', {
        options: {
          format: exportForm.value.format,
          dateRange: exportForm.value.dateRange.length === 2 ? exportForm.value.dateRange : null,
          fields: exportForm.value.fields
        },
        filePath
      })
      
      ElMessage.success('数据已成功导出到: ' + filePath)
      exportDialogVisible.value = false
    }
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error(`导出失败: ${error}`)
  }
}

// 删除数据
const deleteData = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条数据吗？此操作不可恢复。', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const { invoke } = await import('@tauri-apps/api/core')
    await invoke('delete_data', { ids: [id] })
    
    ElMessage.success('数据已删除')
    fetchDetailData() // 刷新详细数据
    fetchDataOverview() // 刷新概览数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除数据失败:', error)
      ElMessage.error(`删除失败: ${error}`)
    }
  }
}

// 打开URL
const openUrl = async (url: string) => {
  try {
    if (!url) {
      ElMessage.warning('链接为空，无法打开')
      return
    }
    
    const { invoke } = await import('@tauri-apps/api/core')
    // 使用Tauri的shell命令打开URL
    await invoke('openweb', { url })
  } catch (error) {
    console.error('打开URL失败:', error)
    ElMessage.error(`打开链接失败: ${error}`)
    
    // 备用方案：尝试使用window.open
    try {
      window.open(url, '_blank')
    } catch (e) {
      console.error('备用方案也失败了:', e)
    }
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchDataOverview()
})
</script>

<style scoped>
.data-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.data-table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-header {
  margin-bottom: 15px;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.stat-content {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: var(--el-color-primary);
  margin-bottom: 8px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

/* 详细数据对话框样式 */
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-actions {
  display: flex;
  gap: 10px;
}

.engagement-data {
  display: flex;
  gap: 15px;
}

.engagement-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-data {
  padding: 30px 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-view {
    padding: 10px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .engagement-data {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
